//
//  YFComposeView.swift
//  微博
//
//  Created by 余仿 on 16/4/15.
//  Copyright © 2016年 YF. All rights reserved.
//

import UIKit

import pop

class YFComposeView: UIView {

    /// MARK:记录外部传进来的控制器
    weak var innertarget:UIViewController?

    func show(target:UIViewController){

        innertarget = target

        target.view.addSubview(self)
    }

    /// MARK: 按钮数组
    private lazy var btnArray:[YFConposeButton] = [YFConposeButton]()

    /// MARK:按钮用到的模型数组
    var composeList:[YFCompose] = {

        //获取plist路径
        let path = NSBundle.mainBundle().pathForResource("Compose.plist", ofType: nil)
        //根据路径创建字典数组
        let composeArray = NSArray(contentsOfFile: path!) as! [[String:String]]

        //遍历字典数组,取出每一个字典,转成模型
        var tempArray = [YFCompose]()

        for dict in composeArray{

            let model = YFCompose(dict: dict)

            tempArray.append(model)
        }

        return tempArray
    }()

    override init(frame: CGRect) {

        let rect = UIScreen.mainScreen().bounds

        super.init(frame: rect)

        //添加子控件
        setupUI()
        //布局
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    func  setupUI(){

        addSubview(bgCover)

        addSubview(logoView)


        bgCover.snp_makeConstraints { (make) -> Void in

            make.edges.equalTo(self)
        }

        logoView.snp_makeConstraints { (make) -> Void in

            make.centerX.equalTo(self)

            make.top.equalTo(self.snp_top).offset(100)
        }
        addChildButtons()
    }


    /// MARK:磨砂背景图
    private lazy var bgCover:UIImageView = UIImageView(image: UIImage.cutImage().applyLightEffect())

    /// MARK:logo
    private lazy var logoView:UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))

    /**
     点击屏幕将当前视图从根窗口上移除
     */
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        for (index,btn) in btnArray.reverse().enumerate(){

            if index == btnArray.count - 1{

                let anString = popAnimation(500, btn: btn, index: index)
                anString.completionBlock = { (anim:POPAnimation!,finish:Bool) -> Void in
                    self.removeFromSuperview()
                }
            }else{
                popAnimation(500, btn: btn, index: index)
            }
        }
    }



    override func willMoveToSuperview(newSuperview: UIView?) {

        btnAppear()
    }



    private func addChildButtons(){
        // MARK: - 按钮相关

        let btnWidth:CGFloat = 80
        let btnHeight:CGFloat = 110
        /// 每一列按钮的个数
        let btnCounts:Int = 3
        /// 行间距
        let btnMargin:CGFloat = (screenWidth - CGFloat(btnCounts) * btnWidth) / CGFloat(btnCounts + 1)
        /// 初始rect
        let btnRect:CGRect = CGRect(x: 0, y: 0, width: btnWidth, height: btnHeight)
        //创建按钮
        for i in 0..<composeList.count{

            let compose = self.composeList[i]

            let btn = YFConposeButton(title: compose.title, imageName: compose.icon!)

            btn.titleLabel?.textAlignment = .Center

            //计算行和列
            //行
            let row = i / btnCounts
            //列
            let col = i % btnCounts

            let dx = btnMargin + CGFloat(col) * (btnMargin + btnWidth)

            let dy = CGFloat(row) * (btnMargin + 10 + btnWidth) + screenHeigth

            btn.frame = CGRectOffset(btnRect, dx, dy)

            btn.setBackgroundImage(nil, forState: .Normal)

            btn.setBackgroundImage(nil, forState: .Highlighted)

            addSubview(btn)

            btnArray.append(btn)

            //绑定点击事件
            btn.addTarget(innertarget, action: "btnDidClick:", forControlEvents: .TouchUpInside)
            //绑定tag
            btn.tag = i

        }
    }


    func btnDidClick(sender:UIButton){
        //1.按钮点击的动画
        //被点击的按钮放大,其他按钮缩小

        UIView.animateWithDuration(0, animations: { () -> Void in

            for btn in self.btnArray{

                if btn == sender{
                    btn.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    btn.transform = CGAffineTransformMakeScale(0.1, 0.1)
                }
                btn.alpha = 0
            }

            }) { (_) -> Void in


                //根据字符串跳转控制器
                //0.取出字符串
                guard let classNameStr = self.composeList[sender.tag].target else{

                    print("classNameStr为空")

                    return
                }

                //1.将字符串转成class类型的对象,
                let className = NSClassFromString(classNameStr) as! UIViewController.Type

                //2.根据类型创建对象
                let targetVc = className.init()

                let nav = UINavigationController(rootViewController: targetVc)
                //                3.跳转控制器
                self.innertarget?.presentViewController(nav, animated: true){(_) -> (Void) in

                    self.removeFromSuperview()
                }
        }

    }

    //按钮出来和消失的pop动画
    private func popAnimation(delta:CGFloat,btn:UIButton,index:Int) -> POPSpringAnimation{

        let anSpring = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
        anSpring.toValue = btn.frame.origin.y + delta
        anSpring.springBounciness = 10
        anSpring.beginTime = CACurrentMediaTime() + Double(index) * 0.09
        btn.pop_addAnimation(anSpring, forKey: "position")
        return anSpring
    }


    //MARK:按钮将要出现
    private func btnAppear(){

        for (index,btn) in btnArray.enumerate(){

            popAnimation(-300, btn: btn, index: index)

        }
    }
}
